<template>
  <div>
    <new-search-bar ref="search" :showSelect="true" :selectList="selectList" @search="startSearch" @cancel="cancleSearch" @changeSelect="changeSelect" :searchText="searchText"></new-search-bar>
    <div v-if="tabList.length > 0" class="c-flex-row c-aligni-center c-ph24 c-justify-sb c-box-shadow10">
      <my-small-tabbar :styleType="2" class="c-bg-white c-ww480" :tabHeight="56" :tabList="tabList" :tabIndex="tabIndex" @changeTab="changeType"></my-small-tabbar>
      <div class="c-fs22 c-fc-xblack" @click="changeSort">{{sortBy == 1 ? '综合排序' : '最近更新'}}</div>
    </div>
    <template v-if="isSearching">
      <div class="c-fs24 c-fc-xblack c-ph24 c-fw-b c-pv24 c-w100 c-flex-row c-aligni-center c-justify-sb">历史搜索
        <span class="iconfont c-fs24 c-fc-gray" @click="deleteAll">&#xe6b3;</span>
      </div>
      <div class="c-flex-row c-flexw-wrap c-pl24 c-pr50 c-p" :class="showMore && downBtn ? 'c-maxh110 c-text-hidden' : ''" ref="searchBox">
        <div class="c-fs22 c-fc-gray c-hh36 c-lh36 c-ww36 c-bg-sgray c-brp50 c-textAlign-c iconfont c-pa c-p-r24 c-p-b16" v-if="showMore && searchLog && searchLog.length > 0" :class="[showMore ? 'icon-xiafangxiang' : '',downBtn == false ? 'icon-shangfangxiangjian' : (downBtn == true ? 'icon-xiafangxiang' : '')]" @click="changeBtn()"></div>
        <div @click="startSearch({searchValue: item, fromLog: true})" v-for="(item,index) in searchLog" :key="index" class="c-maxw">
          <div v-if="item && item.length > 0" class="c-fs20 c-fc-xblack c-ph20 c-mr12 c-bg-sgray c-br18 c-mb22 c-text-ellipsis1 c-hh40 c-lh40">{{item}}</div>
        </div>
      </div>
    </template>
    <div class="c-bg-white c-ph24" v-if="tabList && tabList.length > 0">
      <template v-if="tabList.find(item => item.index == tabIndex) && tabList.find(item => item.index == tabIndex).list">
        <div v-for="(item, index) in tabList.find(item => item.index == tabIndex).list" :key="index" class="c-mt32">
          <template v-if="tabIndex == 1">
            <div @click="clickItem(item.prodId,item.prodType,item.srhSort)">
              <div class="c-flex-row c-justify-sb c-aligni-center">
                <div class="c-ww100 c-hh100 c-brp50 c-mr16 c-text-hidden c-p" v-if="item.prodType == ckFrom.social || item.prodType == ckFrom.qa || item.prodType == ckFrom.answer">
                  <img :src="$addXossFilter(item.avatar, require('../../../assets/defult270.png'))" class="c-w100 c-h img-pe-none">
                  <div class="c-pa c-p-b8 c-p-r8 c-br8 c-fs18 c-fc-white c-ph5 c-hh28 c-flex-row c-flex-center c-translucent-balck50">{{srhSortMap[item.srhSort]}}</div>
                </div>
                <div class="c-ww210 c-hh140 c-br10 c-mr20 c-text-hidden c-p" v-else>
                  <CoverImg :coverSizeClass="'c-w100 c-h c-br6 c-text-hidden'" imgClass="c-br6" :coverUrl="$addXossFilter(item.avatar)" />
                  <div class="c-pa c-p-b8 c-p-r8 c-br8 c-fs18 c-fc-white c-ph5 c-hh28 c-flex-row c-flex-center c-translucent-balck50">{{srhSortMap[item.srhSort]}}</div>
                </div>
                <div class="c-flex-grow1 c-w0 c-flex-column c-justify-sb c-maxh140 c-text-hidden" :class="item.prodType == ckFrom.social || item.prodType == ckFrom.qa || item.prodType == ckFrom.answer ? 'c-ww312 c-pt10' : ''">
                  <div class="c-fs24 c-lh34 c-fc-xblack" :class="item.prodType == ckFrom.social || item.prodType == ckFrom.qa || item.prodType == ckFrom.answer ? 'c-text-ellipsis1 c-mb20' : 'c-text-ellipsis2 c-mb36'" v-html="item.name"></div>
                  <div class="c-fs24 c-lh34 theme-fc">
                    <template v-if="item.prodType == ckFrom.circle">
                      <span v-if="item.payType == 2">{{'￥' | iosPriceFilter}}</span>
                      {{item.payType | priceValueFilter(item.price, ckFrom.circle)}}
                    </template>
                    <template v-else>
                      <div v-if="item.isSaleTogether==1 || (item.isSaleTogether==1 && item.isEncrypt == 1)">关联售卖
                        <span class="c-fs20" v-if="(item.srhSort == 10 || item.srhSort == 11) && item.isPreview == 1">{{item.srhSort == 10 ? '/支持试看' : '/支持试听'}}</span>
                      </div>
                      <div v-else-if="item.isEncrypt == 1">加密</div>
                      <div v-else-if="item.isEncrypt == -1 && item.payType == 5">指定购买</div>
                      <div v-else-if="item.isEncrypt == -1 && item.payType == 6">指定学员</div>
                      <div v-else>
                        <span v-if="item.price && Number(item.price) > 0">{{'￥' | iosPriceFilter}}</span>
                        <!-- 约课没有payType定义 -->
                        <span v-if="item.prodType == ckFrom.reservation">{{item.price | moneyStr}}</span>
                        <span v-else>{{item.payType | priceValueFilter(item.price, item.prodType, item.optimal, 'index')}}</span>
                        <span class="c-fs20" v-if="(item.srhSort == 10 || item.srhSort == 11) && item.isPreview == 1">{{item.srhSort == 10 ? '/支持试看' : '/支持试听'}}</span>
                      </div>
                    </template>
                  </div>
                </div>
                <div class="c-pv8 theme-bg c-fc-white c-fs20 c-lh28 c-br24 c-ph30" v-if="item.prodType == ckFrom.social || item.prodType == ckFrom.qa || item.prodType == ckFrom.answer">
                  {{(item.prodType == ckFrom.social ? '加入' : (item.prodType == ckFrom.answer ? '查看答案' : '提问'))}}
                </div>
              </div>
            </div>
          </template>
          <template v-else-if="tabIndex == 2">
            <div @click="clickShop(item.mgId)" class="c-flex-row c-justify-sb c-aligni-center">
              <div class="c-hh180 c-ww180 c-text-hidden">
                <CoverImg :coverSizeClass="'c-w100 c-h c-br6 c-text-hidden'" imgClass="c-br6" :coverUrl="$addXossFilter(item.avatar)" />
              </div>
              <div class="c-pl20 c-flex-grow1 c-flex-column c-w0 c-justify-sb c-hh180 c-justify-sb">
                <div class="c-fs28 c-fc-xblack c-text-ellipsis2 c-pt5"><span v-if="item.flashSales && item.flashSales.sales.status == 2" class="c-fs16 theme-bg c-fc-white c-mr4 c-textAlign-c c-br4 c-pv4 c-ph4">限时{{Number(item.flashSales.price) == 0 ? '免费' : '折扣'}}</span><span v-html="item.name"></span></div>
                <div class="c-pb5">
                  <span class="c-fs24 theme-fc c-fw-b">{{'￥' | iosPriceFilter}}{{item.flashSales && item.flashSales.sales.status ==2 ? item.flashSales.price : item.price}}</span>
                  <span v-if="item.originalPrice * 1 > 0" class="c-fs24 c-fc-sblack c-text-decoration-through c-fw-b c-mr12">{{'￥' | iosPriceFilter}}{{item.originalPrice}}</span>
                </div>
              </div>
            </div>
          </template>
          <template v-else-if="tabIndex == 3">
            <div @click.stop="clickActivityItem(item.activityId)" class="c-bg-white c-br16 c-pb24 c-bd1" :class="index==0 ? '' : 'c-mt30'">
              <div class="c-w100 c-text-hidden c-p c-br-tr16 c-br-tl16 c-p c-pz1">
                <img class="c-w100 c-h-auto imgCloseBig" v-lazy="item.poster || require('../../../assets/activity_defult.png')" :key="item.poster" />
                <div v-if="statusMap[item.enrollStatus == 2 ? 3 : item.status]" class="c-pa c-p-t0 c-p-l0 c-pz2 c-br-tl16 c-br-br16 c-hh32 c-pl12 c-pr10 c-fs20 c-fc-white c-flex-row c-flex-center" :class="statusMap[item.enrollStatus == 2 ? 3 : item.status].bgClass">{{statusMap[item.enrollStatus == 2 ? 3 : item.status].title}}</div>
              </div>
              <div class="c-ph24 c-pt20">
                <div class="c-fs28 c-w100 c-fw600 c-ww-bw c-ww-ba">{{item.name}}</div>
                <div class="c-fs20 c-mt16 c-flex-row c-fc-gray c-justify-sb">
                  <div class="c-flex-row c-aligni-center">
                    <span class="iconfont c-fs20 c-mr8">&#xe680;</span>
                    <span>{{item.enrollStartAt | formatTime}} — {{item.enrollEndAt | formatTime }}</span>
                  </div>
                  <div class="c-flex-row c-aligni-center" v-show="item.isShowEnroll == 1">
                    <span class="iconfont c-fs20 c-mr8">&#xe62a;</span>
                    <span>{{item.enrollTicket}}人</span>
                  </div>
                </div>
                <div class="c-w100 c-flex-row c-justify-sb" :class="item.city || item.province || item.isRefund==1 && !(item.price.split('~')[0]==item.price.split('~')[1] && (Number(item.price.split('~')[0])==0)) ? 'c-mt16' : ''">
                  <!-- 活动的地址 -->
                  <div class="c-flex-row c-aligni-center" v-if="item.city">
                    <span class="iconfont c-fs20 c-fc-gray c-mr8">&#xe90f;</span>
                    <span class="c-fs20 c-fc-gray">{{item.city}}</span>
                  </div>
                  <div class="c-flex-row c-aligni-center" v-else-if="item.province">
                    <span class="iconfont c-fs20 c-fc-gray c-mr8">&#xe90f;</span>
                    <span class="c-fs20 c-fc-gray">{{item.province}}</span>
                  </div>
                </div>
                <!-- 价格 -->
                <div class="c-fs26 c-fc-xmlred c-mt14 c-flex-row c-aligni-center">
                  <span class="c-fw600 c-mr20" v-if="item.price && item.isShowPrice == 1">
                    <span class="c-fs22" v-if="checkPrice(item.price) > 1">{{'￥' | iosPriceFilter}}</span>
                    <span v-if="checkPrice(item.price) == 1" class="c-fs28">免费</span>
                    <span class="c-fs36" v-else-if="!$isWxAppIos()" v-html="$getPriceStyleHtml(item.price.split('~')[0], false, 7, 'c-fs24')"></span>
                    <span v-if="!$isWxAppIos() && checkPrice(item.price) == 3" class="c-fs20 c-ml4">起</span>
                  </span>
                  <span class="c-mr20 c-br4 c-ph10 c-hh28 c-fc-xmlred c-bd1-xmlred c-bg-xmlred-10 c-fs18 c-inlineblack c-textAlign-c" v-if="item.price && item.isShowPrice == 1 && !$isWxAppIos() && item.vipMaxDiscount != null">会员减{{item.vipMaxDiscount}}元</span>
                  <span class="c-br4 c-ph10 c-hh28 c-fc-white theme-bg c-fs18 c-inlineblack c-textAlign-c" v-if="item.isRefund==1 && !(item.price.split('~')[0]==item.price.split('~')[1] && (Number(item.price.split('~')[0])==0))">签到退款</span>
                </div>
              </div>
            </div>
          </template>
          <template v-else-if="tabIndex == 4">
            <div @click="goDetail(item.Id)" class="c-flex-row c-justify-sb c-aligni-center">
              <div class="c-ww240 c-hh160 c-br16 c-text-hidden c-p">
                <CoverImg coverSizeClass="c-w100 c-h c-text-hidden c-br16" imgClass="c-br16" :coverUrl="$addXossFilter(item.productImage && item.productImage.length > 0 ? item.productImage[0] : null, require('../../../assets/defult270.png'))" />
                <div class="c-fs16 c-fc-white c-ph4 c-hh24 c-br4 c-flex-row c-flex-center bg-black-opacity c-pa c-p-b10 c-p-r10">{{item.type == 1 ? '兑换券' : item.type == 2 ? '无门槛券' : item.type == 3 ? '满减券' : item.type == 4 ? '抵价券' : item.type == 5 ? '折扣券' : ''}}</div>
              </div>
              <div class="c-w0 c-flex-grow1 c-flex-column c-ml20 c-pb24 c-bd-b1 c-h c-">
                <div class="c-fs24 c-fc-xblack c-text-ellipsis1">{{item.productName}}</div>
                <div class="c-fs22 c-fc-gray c-mt10 c-text-ellipsis1">{{item.scope}}</div>
                <div class="c-fs22 c-fc-gray c-mt10">
                  {{item.type == 1 ? '兑换商品' : item.type == 4 ? '抵扣全额' : item.type == 5 ? (Number(item.amount) > 0 ? ('满' + Number(item.amount) + '元打' + Number(item.price) + '折') : ('无门槛打' + Number(item.price) + '折')) : (Number(item.amount) > 0 ? ('满' + Number(item.amount) + '元减' + Number(item.price) + '元') : '无使用门槛')}}
                  <span v-if="item.type == 5 && !!item.enableTotalAmount == 1">{{ `，最高可减${item.totalAmount}元` }}</span>
                </div>
                <div class="c-flex-row c-justify-sb c-aligni-center c-mt10">
                  <div class="c-fs26 c-fc-xmlred c-fw600"><span v-if="item.productPrice > 0" class="c-fs20">{{'￥' | iosPriceFilter}}</span>{{Number(item.productPrice).toFixed(2) | moneyStr}}</div>
                  <div class="c-fs20 c-fc-white c-ww110 c-hh40 c-flex-row c-flex-center c-br20 theme-bg">去抢购</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
    </div>
    <loading-status-tem class="notext" :noData="!tabList || tabList && tabList.length == 0" :noDataText="'输入关键词，查找想要的内容'" noneImage="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/index/nosearch.png">
    </loading-status-tem>
    <loading-status-tem :dataStatus="tabList.find(item => item.index == tabIndex).loadingStatus" :noDataText="''" :isFromSearch="true" v-if="tabList && tabList.length > 0">
      <p class="c-textAlign-c c-fc-xblack c-fs24 c-lh24" v-if="tabList.find(item => item.index == tabIndex).loadingStatus == 'NO_DATA'">没有找到“<span class="theme-fc">{{searchText}}</span>”相关内容</p>
    </loading-status-tem>
  </div>
</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import CoverImg from '@/components/templates/common/coverImg.vue';
import { COUPON_SCOPE_MAP } from "@/utils/constant.js";
import { utilJs } from "@/utils/common.js";
import { goDetails } from "@/utils/goDetails.js";
// srhSort排序
// 课程5: 视频10音频11图文12, 专栏: 20, 知识套餐: 30, 直播: 公开课40小班课41, 训练营: 50, 社群: 60, 打卡: 70, 活动: 80,
// 商城商品: 90, 考试: 100(101,102), 练习: 110, AI测评: 120(104), 测评专题: 130, 互动测评: 140(103), 资料: 150, 问答:160
const LIMIT = 10;
let couponScopeMap = COUPON_SCOPE_MAP;
const map = {
  1: '知识产品',
  2: '实体商品',
  3: '活动',
  4: '有价券',
}
export default {
  name: "SearchList",
  components: {
    loadingStatusTem,
    newSearchBar,
    MySmallTabbar,
    CoverImg
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      from: 1,
      searchDataStatus: 'HAS_MORE_DATA',
      shopDataStatus:  'HAS_MORE_DATA',
      searchText: "",
      searchList: [], // 搜索内容
      shopList: [], // 商城搜索
      searchLog: [], // 搜索记录
      srhSortMap: {
        '10': '视频',
        '11': '音频',
        '12': '图文',
        '20': '专栏',
        '30': '知识套餐',
        '40': '公开课',
        '41': '小班课',
        '50': '训练营',
        '53': '约课',
        '60': '社群',
        '70': '打卡',
        '80': '活动',
        '90': '商城商品',
        '101': '考试',
        '102': '考试',
        '110': '练习',
        '104': 'AI测评',
        '130': '测评专题',
        '103': '互动测评',
        '150': '资料',
        '160': '问答',
        '170': '电子书',
        '180': '直播间',
        '181': '圈子'
      },
      downBtn: true,
      showMore: false,
      tabList: [],
      tabIndex: 1,
      selectList: [["名称", "讲师"]],
      searchType: 1, // 搜索类型
      ckFrom: global.ckFrom,
      isSearching: true,
      sortBy: 1, // 1 综合排序 2 最新排序
      isLoading: false,
      isFirstGetList: true, // 判断第一次请求列表
      statusMap: {
        0: {title: '即将报名', bgClass: 'c-bg-38BD05'},
        1: {title: '报名中', bgClass: 'c-bg-38BD05'},
        2: {title: '报名截止', bgClass: 'c-bg-xlyellow'},
        3: {title: '已结束', bgClass: 'c-bg-ccc'} // enrollStatus=2也是已结束，相当于status=3，所以直接用这边的状态
      }
    }
  },
  computed: {
    searchList() {
      if (this.tabList.length == 0 || !this.tabList.find(item => item.index == 1)) return []
      let tab = this.tabList.find(item => item.index == 1); // 1表示知识付费
      return tab ? tab.list : [];
    },
    shopList() {
      if (this.tabList.length == 0 || !this.tabList.find(item => item.index == 2)) return []
      let tab = this.tabList.find(item => item.index == 2); // 2表示商城
      return tab ? tab.list : [];
    },
    activityList() {
      if (this.tabList.length == 0 || !this.tabList.find(item => item.index == 3)) return []
      let tab = this.tabList.find(item => item.index == 3); // 3表示活动
      return tab ? tab.list : [];
    },
    valuableCouponList() {
      if (this.tabList.length == 0 || !this.tabList.find(item => item.index == 4)) return []
      let tab = this.tabList.find(item => item.index == 4); // 4表示有价券
      return tab ? tab.list : [];
    }
  },
  watch: {
    $route(to, from) {
      if (to.path == '/' || to.path == '/homePage/spread/spreadIndex' || to.path == '/homePage/microPage/microPage') {
        this.searchText = "";
        this.tabList = [];
        this.isSearching = true;
        this.sortBy = 1;
      }
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
    this.wechatShare();
  },
  methods: {
    iosAppRouteChange(toPath) {
      if (utilJs.isIOSApp()) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else if (utilJs.isAndoridNewApp()) {
        let data = {
          path: toPath
        }
        window.androidWechatRoute.doAction(JSON.stringify(data))
      } else {
        this.$routerGo(this, "push", { path: toPath });
      }
    },
    // 活动价格展示
    checkPrice(price) { // 1免费 2付费且单价格（不是价格区间，不是￥1.00起这种） 3付费且多价格（有价格区间，￥1.00起这种）
      const startPrice = price.split('~')[0]
      const endPrice = price.split('~')[1]
      if (startPrice == endPrice && (Number(startPrice) == 0) && (Number(endPrice) == 0)) { // 免费
        return 1
      }
      if (Number(startPrice) != 0 && startPrice == endPrice) { // 付费且单价格
        return 2
      }
      if ((Number(startPrice) != 0 || Number(endPrice) != 0) && startPrice != endPrice) { // 付费且多价格
        return 3
      }
    },
    // 跳转活动详情
    clickActivityItem(activityNo) {
      let toPath = `/activity/activityDetail?ActivityNo=${activityNo}&from=activity`;
      this.iosAppRouteChange(toPath);
    },
    // 有价券跳转
    goDetail(cId) {
      this.$routerGo(this, "push", {
        path: "/member/myExchange/valuableCoupon",
        query: {id: cId}
      });
    },
    // 清除搜索
    cancleSearch() {
      this.searchText = "";
      this.tabList = [];
      this.isSearching = true;
      this.sortBy = 1;
    },
    // 点击综合排序/最新更新
    changeSort() {
      this.sortBy = this.sortBy == 1 ? 2 : 1;
      this.startSearch({searchValue: this.searchText, selectItem: this.searchType}, true, this.tabIndex);
    },
    // 切换名称讲师搜索
    changeSelect(e) {
      this.searchType = ('讲师').includes(e) ? 2 : 1;
      // 讲师搜索只显示知识产品
      this.tabList = ('讲师').includes(e) ? this.tabList.filter(item => { return item.index == 1 }) : this.tabList;
    },
    // 切换类型
    async changeType(type) {
      if ((this.searchDataStatus == 'LOADING') || (this.tabIndex == type)) {
        return;
      }
      console.log('tabIndex: ' + type);
      const imageElement = document.getElementById(`tab-${type}`)
      if (imageElement) {
        imageElement.scrollIntoView({
          behavior: 'smooth',
          block: 'nearest',
          inline: 'start'
        })
      }
      this.tabIndex = type;
      let tab = this.tabList.find(item => item.index == this.tabIndex);
      // 搜索最新更新跟综合排序切换tab的时候，sortBy不对应时，按照当前的更新此列表
      if (tab && tab.sortBy && tab.sortBy != this.sortBy) {
        let tabIndex = this.tabIndex;
        let that = this;
        let tabList = that.tabList;
        tabList.forEach(item => {
          if (item.index == tabIndex) {
            item.list = [];
            item.page = 1;
            item.sortBy = this.sortBy;
            item.loadingStatus = 'NO_DATA'
          }
        })
        that.tabList = JSON.parse(JSON.stringify(tabList))
        try {
          // 请求知识付费内容
          if (tabIndex == 1) {
            await that.getMore();
          } else if (tabIndex == 2) {
            // 请求实体商品
            await that.getGoods();
          } else if (tabIndex == 3) {
            // 请求活动
            await that.getActivityList();
          } else {
            // 请求有价券
            await that.getListValuableCoupon();
          }
        } finally {
          that.isFirstGetList = false;
        }
        return
      }
      // 接口有请求对应得搜索内容就不在重复请求
      if (tab && tab.search && this.searchText && (tab.search != this.searchText)) {
        if (this.tabIndex == 1) {
          this.getMore();
        } else if (this.tabIndex == 2) {
          this.getGoods();
        } else if (this.tabIndex == 3) {
          this.getActivityList();
        } else if (this.tabIndex == 4) {
          this.getListValuableCoupon();
        }
      }
    },
    // 删除全部搜索记录
    deleteAll() {
      let that = this;
      that.$cjConfirm({
        title: '', //
        titleCenter: true, //标题是否居中
        message: '确认删除全部历史记录？',
        messageCenter: true, //内容是否居中
        showMasker: true, //是否显示透明背景
        clickCloseModal: false, //是否点击透明背景关闭弹窗
        showCancelButton: true, //是否显示取消按钮
        cancelButtonText: '', //取消按钮文本
        confirmButtonText: '', //确认按钮文本
        onConfirm() {
          utilJs.getMethod(global.apiurl + "goods/delSearch", (res) => {
            that.searchLog = [];
          });
        },
        onCancel() {
        },
      })
    },
    // 改变按钮方向
    changeBtn() {
      this.downBtn = !this.downBtn;
    },
    // 获取搜索记录列表
    getSearchLog() {
      utilJs.getMethod(global.apiurl + "goods/getSearchList", (res) => {
        this.searchLog = res;
        this.$nextTick(() => {
          if (this.$refs.searchBox && this.$refs.searchBox.clientHeight >= 90) {
            this.showMore = true;
          }
        })
      });
    },
    clickShop(shopNo) {
      this.$routerGo(this, "push", {
        path: "/mall/shopDetail/shopDetail",
        query: {
          shopNo: shopNo
        }
      });
    },
    //通过名称模糊搜索
    async startSearch(e, isSort = false, tabIndex) {
      this.searchType = e.selectItem && e.selectItem == '讲师' ? 2 : this.searchType;
      let enableMallModule = localStorage.getItem('companyAuth') ? JSON.parse(localStorage.getItem('companyAuth')).enableMallModule : 0;
      this.searchText = e.searchValue;
      if (this.searchText == '') {
        this.$showCjToast({
          text: "请输入搜索内容",
          type: "warn",
          time: 1000
        });
        return
      }
      this.isLoading = false;
      let that = this;
      if (!tabIndex) {
        that.tabList = [];
        that.isFirstGetList = true; // 判断第一次请求列表
        try {
          // 请求知识付费内容
          await that.getMore();
          // 请求实体商品
          if (that.searchType != 2 && enableMallModule == 1) await that.getGoods();
          // 请求活动
          await that.getActivityList();
          // 请求有价券
          await that.getListValuableCoupon();
        } finally {
          that.isFirstGetList = false;
        }
      } else {
        let tabList = that.tabList;
        tabList.forEach(item => {
          if (item.index == tabIndex) {
            item.list = [];
            item.page = 1;
            item.loadingStatus = 'NO_DATA'
          }
        })
        that.tabList = JSON.parse(JSON.stringify(tabList))
        try {
          // 请求知识付费内容
          if (tabIndex == 1) {
            await that.getMore();
          } else if (tabIndex == 2) {
            // 请求实体商品
            await that.getGoods();
          } else if (tabIndex == 3) {
            // 请求活动
            await that.getActivityList();
          } else {
            // 请求有价券
            await that.getListValuableCoupon();
          }
        } finally {
          that.isFirstGetList = false;
        }
      }
    },
    // 设置tabList
    setTabList(data) {
      let {index, list, page, loadingStatus, sortBy} = data;
      let tabList = this.tabList || [];
      let tab = {
        title: map[index],
        index: index,
        searchText: this.searchText,
        list: list,
        page: page,
        sortBy: sortBy,
        loadingStatus: loadingStatus
      }
      if (tabList.length == 0 || !tabList.find(item => item.index == index) == null) {
        tabList = [tab]
      } else if (tabList.find(item => item.index == index)) {
        tabList.forEach((item, i) => {
          if (item.index == index) {
            tabList[i] = tab
          }
        })
      } else {
        tabList.push(tab)
      }
      this.tabList = JSON.parse(JSON.stringify(tabList));
      this.isSearching = false;
      this.tabIndex = this.isFirstGetList ? this.tabList[0].index : index;
    },
    // 获取实体商品数据
    getListValuableCoupon() {
      return new Promise((resolve, reject) => {
        if (this.isLoading) {
          return;
        }
        this.isLoading == true;
        this.$loading.show();
        let data = this.tabList.find(item => item.index == 4);
        let page = data ? data.page : 1;
        let list = data ? data.list : null;
        let sortBy = data ? data.sortBy : 1;
        let loadingStatus = data ? data.loadingStatus : " NO_MORE_DATA";
        let query = {limit: LIMIT, page: page, searchName: this.searchText, ckFrom: 2};
        if (this.sortBy == 2) {
          query.orderByUpdated = 1;
        }
        utilJs.postMethod(`${global.apiurl}valuablecoupons/listValuableCoupon`, query,
          res => {
            if (res.retData && res.retData.data && res.retData.data.length > 0) {
              res.retData.data.forEach(eItem => {
                if (eItem.type == 1) {
                  eItem.scope = eItem.name;
                } else if (eItem.type == 4) {
                  eItem.scope = "适用于预约师资功能";
                } else {
                  if (eItem.redeemType == 27) {
                    eItem.prodTypes = eItem.prodTypes ? eItem.prodTypes.split(",") : '';
                    if (eItem.prodTypes && eItem.prodTypes.length > 0) {
                      for (let i = 0; i < eItem.prodTypes.length; i++) {
                        eItem.prodTypes[i] = couponScopeMap[eItem.prodTypes[i]];
                      }
                    }
                  }
                  eItem.scope = eItem.redeemType == 26 ? '全店商品可用' : (eItem.redeemType == 25 ? '适用于商城商品' : eItem.redeemType == 27 ? ('适用于' + (eItem.prodTypes ? eItem.prodTypes.join('、') : '')) : '指定商品可用')
                }
                try {
                  eItem.productImage = JSON.parse(eItem.productImage)
                } catch (err) {
                  console.log(err.message)
                }
              });
            }
            if (page == 1) {
              list = res.retData && res.retData.data ? res.retData.data : [];
            } else {
              list = list.concat(res.retData.data);
            }
            if (res.retData.data && (res.retData.data.length < LIMIT)) {
              loadingStatus = page == 1 && res.retData.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            } else {
              loadingStatus = 'HAS_MORE_DATA';
              page++;
            }
            this.isLoading = false;
            if (list && list.length > 0) {
              let data = {
                index: 4,
                list: list,
                page: page,
                sortBy: sortBy,
                loadingStatus: loadingStatus
              }
              this.setTabList(data)
            }
            this.isLoading == false;
            resolve(list && list.length > 0 ? true : false)
          },
          failRes => {
            this.$loading.hide();
            this.isLoading = false;
            resolve(false)
          }
        )}
      )
    },
    // 获取活动列表
    getActivityList() {
      return new Promise((resolve, reject) => {
        if (this.isLoading) return
        this.isLoading == true;
        this.$loading.show();
        let data = this.tabList.find(item => item.index == 3);
        let page = data ? data.page : 1;
        let list = data ? data.list : null;
        let sortBy = data ? data.sortBy : 1;
        let loadingStatus = data ? data.loadingStatus : " NO_MORE_DATA";
        let query = {pageSize: LIMIT, pageIndex: page, name: this.searchText, ckFrom: 2};
        if (this.sortBy == 2) {
          query.orderByUpdated = 1;
        }
        utilJs.postMethod(
          global.apiurl + "activities/mlists", query, res => {
            if (page == 1) {
              list = res.data;
            } else {
              list = [...list, ...res.data];
            }
            if (res.data && (res.data.length < LIMIT)) {
              loadingStatus = page == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            } else {
              loadingStatus = 'HAS_MORE_DATA';
              page++;
            }
            if (list && list.length > 0) {
              let data = {
                index: 3,
                list: list,
                page: page,
                sortBy: sortBy,
                loadingStatus: loadingStatus
              }
              this.setTabList(data)
            }
            this.isLoading = false;
            resolve(list && list.length > 0 ? true : false)
          }, failRes => {
            this.$loading.hide();
            this.isLoading = false;
            resolve(false)
          })
        }
      )
    },
    // 获取实体商品数据
    getGoods() {
      return new Promise((resolve, reject) => {
        if (this.isLoading || (this.searchType && this.searchType == 2)) {
          return;
        }
        this.isLoading == true;
        this.$loading.show();
        let data = this.tabList.find(item => item.index == 2);
        let page = data ? data.page : 1;
        let list = data ? data.list : null;
        let sortBy = data ? data.sortBy : 1;
        let loadingStatus = data ? data.loadingStatus : " NO_MORE_DATA";
        let getUrl = global.apiurl + "goods?q=" + encodeURIComponent(this.searchText) + "&page=" + page;
        if (this.sortBy == 2) {
          getUrl = getUrl + '&o=updatedAt';
        }
        utilJs.getMethod(getUrl, res => {
          if (page == 1) {
            list = res.goods.data;
          } else {
            list = [...list, ...res.goods.data];
          }
          if (this.searchText) {
            for (let i = 0; i < list.length; i++) {
              list[i].name = list[i].name.replaceAll(this.searchText, "<span class='theme-fc'>" + this.searchText + "</span>");
            }
          }
          if (res.goods.total * 1 == res.goods.to * 1) {
            loadingStatus = res.goods.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            loadingStatus = 'HAS_MORE_DATA';
            page++;
          }
          this.$loading.hide()
          if (list && list.length > 0) {
            let data = {
              index: 2,
              list: list,
              page: page,
              sortBy: sortBy,
              loadingStatus: loadingStatus
            }
            this.setTabList(data)
          }
          this.isLoading = false;
          resolve(list && list.length > 0 ? true : false)
        }, failRes => {
          this.$loading.hide();
          this.isLoading = false;
          resolve(false)
        });
      })
    },
    //分页获取知识产品列表
    getMore() {
      return new Promise((resolve, reject) => {
        if (this.isLoading) {
          return;
        }
        this.isLoading == true;
        let tab = this.tabList.find(item => item.index == 1);
        let page = tab ? tab.page : 1;
        let list = tab ? tab.list : null;
        let sortBy = tab ? tab.sortBy : 1;
        let loadingStatus = tab ? tab.loadingStatus : " NO_MORE_DATA";
        let data = {
          name: this.searchText,
          from: page,
          size: LIMIT,
          type: this.searchType
        }
        this.$loading.show()
        let getUrl = `${global.apiurl}common/globalSearch`
        if (this.sortBy == 2) {
          getUrl = getUrl + '?order=updatedAt&sort=desc';
        }
        utilJs.postMethod(getUrl, data, res => {
          this.total = res.length == 0 && res && !res.total ? 0 : res.total * 1;
          if (page == 1) {
            list = res.data && res.data.length > 0 ? res.data : [];
          } else {
            list = [...list, ...res.data];
          }
          if (this.searchText) {
            for (let i = 0; i < list.length; i++) {
              list[i].name = list[i].name.replaceAll(this.searchText, "<span class='theme-fc'>" + this.searchText + "</span>");
            }
          }
          if (!res.total || (list != null && res.total == list.length)) {
            loadingStatus = !res.total ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            loadingStatus = 'HAS_MORE_DATA';
            page++;
          }
          if (list && list.length > 0) {
            let data = {
              index: 1,
              list: list,
              page: page,
              sortBy: sortBy,
              loadingStatus: loadingStatus
            }
            this.setTabList(data)
          }
          this.$loading.hide()
          this.isLoading = false;
          resolve(list && list.length > 0 ? true : false)
        }, failRes => {
          this.searchDataStatus = 'DATA_ERROR';
          this.$loading.hide()
          this.isLoading = false;
          resolve(false)
        });
      })
    },
    //点击列表跳转
    clickItem(id, type, srhSort) {
      type = type == global.ckFrom.live ? (srhSort == 40 ? global.ckFrom.live : global.ckFrom.privateClass) : type;
      srhSort = srhSort == 11 ? 1 : srhSort == 12 ? 2 : 0;
      goDetails(this, type, id, '', srhSort);
    },
    //分享
    wechatShare: function () {
      let title = "搜索";
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?type=0&refereeId=${localStorage.getItem("userId")}`;
      utilJs.wechatConfig(shareUrl, title, "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let title = "搜索";
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?type=0&refereeId=${localStorage.getItem("userId")}`;
      utilJs.appShareTrue(title, "", shareUrl, "");
    },
    //下滑获取更多
    windowScrollFunction: function () {
      if (!this.tabList || (this.tabList && this.tabList.length == 0)) return
      utilJs.handleLoading(() => {
        let tab = this.tabList.find(item => item.index == this.tabIndex);
        if (tab && tab.loadingStatus == 'HAS_MORE_DATA') {
          if (this.tabIndex == 1) {
            this.getMore();
          } else if (this.tabIndex == 2) {
            this.getGoods();
          } else if (this.tabIndex == 3) {
            this.getActivityList();
          } else if (this.tabIndex == 4) {
            this.getListValuableCoupon();
          }
        }
      });
    },
  },
  activated() {
    setDocumentTitle("搜索");
    this.$store.commit('updateLoadingStatus', {
      isLoading: false
    });
    this.searchType = 1;
    this.isFirstGetList = true;
    this.getSearchLog();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<style scoped>
.c-mb36 {
  margin-bottom: 0.9rem;
}
.notext img{
  width: 45%;
  margin: 0 auto;
}
</style>


